<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Models\AdminUser as User;
use App\Models\Wechat;
use App\Models\WechatGroup;
use App\Models\WechatGroupUser;
use App\Models\RoleUser;
use App\Models\Group;
use App\Http\Controllers\Admin\DomainController;
use App\Models\WechatRecover;

class WechatController extends Controller
{
    protected $fields = [
        'uid' => 1,
        'username' => '',
        'wx_num' => '',
        'wx_nike' => '',
        'group' => '',
        'max_rand' => 10,
        'online_time' => null,
        'offline_time' => null,
        'status' => 1,
        'phone' => '',
        'tid' =>0,
    ];

    public function __construct(Request $request)
    {
        /*   $this->uid = auth()->user()->id;
          $condition = [['wechats.uid', '>', 0],];
          if($this->uid > 1){
              $condition = array('wechats.uid'=>$this->uid);

          }
          $this->condition = $condition; */
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index(Request $request,$gid=-1)
    {

        $uid = auth()->user()->id;
        if(getRoleName($uid)=='客服主管'){
            $condition = [$uid,auth()->user()->pid];
        }else{
            $condition = [$uid];
        }
        $this->condition = $condition;
        //查询所有属于我、下级、授权的分组
        $wechat_groups_ids = WechatGroup::getWechatGroupCids($uid,'id');
        //$groups = WechatGroupUser::where('uid',auth()->user()->id)->lists('gid')->toArray();
        if ($request->ajax()) {
            $data = array();
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');
            $gid = $request->get('gid', -1);
            $data['recordsTotal'] = Wechat::
            where(function ($query) use ($wechat_groups_ids,$gid){
                if($gid>0){
                    if(getRoleName(auth()->user()->id)=='超级管理员'||auth()->user()->id==1){
                        $query->where('wechats.group',$gid);
                    }else{
                        $query->where('wechats.group',$gid)->whereIn('wechats.group',$wechat_groups_ids);
                    }
                }elseif($gid==0){
                    $query->where('wechats.group',0);
                }else{
                    if(getRoleName(auth()->user()->id)=='超级管理员'||auth()->user()->id==1){
                        //$query->where('wechats.group',0)->orWhereIn('wechats.group',$wechat_groups_ids);
                    }else{
                        $query->where('wechats.group',0)->orWhereIn('wechats.group',$wechat_groups_ids);
                    }
                }
            })->count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = Wechat::leftJoin("wechat_groups", "wechat_groups.id", "=", "wechats.group")->where(function ($query) use ($search) {
                    $query->where('wx_num', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('wx_nike', 'like', '%' . $search['value'] . '%')
                        ->orWhere('wechat_groups.name', 'like', '%' . $search['value'] . '%');
                })->where(function ($query) use ($wechat_groups_ids,$gid){
                    if($gid>0){
                        if(getRoleName(auth()->user()->id)=='超级管理员'||auth()->user()->id==1){
                            $query->where('wechats.group',$gid);
                        }else{
                            $query->where('wechats.group',$gid)->whereIn('wechats.group',$wechat_groups_ids);
                        }
                    }elseif($gid==0){
                        $query->where('wechats.group',0);
                    }else{
                        if(getRoleName(auth()->user()->id)=='超级管理员'||auth()->user()->id==1){
                            //$query->where('wechats.group',0)->orWhereIn('wechats.group',$wechat_groups_ids);
                        }else{
                            $query->where('wechats.group',0)->orWhereIn('wechats.group',$wechat_groups_ids);
                        }
                    }
                })->count();

                $data['data'] = Wechat::select("wechats.*", "wechat_groups.name","admin_users.name as username")
                    ->leftJoin("wechat_groups", "wechat_groups.id", "=", "wechats.group")
                    ->leftJoin("admin_users", "wechat_groups.tid", "=", "admin_users.id")
                    ->where(function ($query) use ($search) {
                        $query->where('wx_num', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('wx_nike', 'like', '%' . $search['value'] . '%')
                            ->orWhere('wechat_groups.name', 'like', '%' . $search['value'] . '%');
                    })
                    ->where(function ($query) use ($wechat_groups_ids,$gid){
                        if($gid>0){
                            if(getRoleName(auth()->user()->id)=='超级管理员'||auth()->user()->id==1){
                                $query->where('wechats.group',$gid);
                            }else{
                                $query->where('wechats.group',$gid)->whereIn('wechats.group',$wechat_groups_ids);
                            }
                        }elseif($gid==0){
                            $query->where('wechats.group',0);
                        }else{
                            if(getRoleName(auth()->user()->id)=='超级管理员'||auth()->user()->id==1){
                                //$query->where('wechats.group',0)->orWhereIn('wechats.group',$wechat_groups_ids);
                            }else{
                                $query->where('wechats.group',0)->orWhereIn('wechats.group',$wechat_groups_ids);
                            }
                        }
                    })
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                /* $data['recordsFiltered'] = Wechat::where(session('authAdminCondition'))->count(); */
                $data['recordsFiltered'] = $data['recordsTotal'];
                $data['data'] = Wechat::select("wechats.*", "wechat_groups.name","admin_users.name as username")
                    ->leftJoin("wechat_groups", "wechat_groups.id", "=", "wechats.group")
                    ->leftJoin("admin_users", "wechat_groups.tid", "=", "admin_users.id")
                    ->where(function ($query) use ($wechat_groups_ids,$gid){
                        if($gid>0){
                            if(getRoleName(auth()->user()->id)=='超级管理员'||auth()->user()->id==1){
                                $query->where('wechats.group',$gid);
                            }else{
                                $query->where('wechats.group',$gid)->whereIn('wechats.group',$wechat_groups_ids);
                            }
                        }elseif($gid==0){
                            $query->where('wechats.group',0);
                        }else{
                            if(getRoleName(auth()->user()->id)=='超级管理员'||auth()->user()->id==1){
                                //$query->where('wechats.group',0)->orWhereIn('wechats.group',$wechat_groups_ids);
                            }else{
                                $query->where('wechats.group',0)->orWhereIn('wechats.group',$wechat_groups_ids);
                            }
                        }
                    })
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            return response()->json($data);
        }
        $data['wechatgroup'] = WechatGroup::getWechatGroupCids($uid,'*');
        $data['role'] = RoleUser::where('user_id',$uid)->first();
        $data['gid']=$gid;
        return view('admin.wechat.index', $data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $userList = User::lists('name', 'id');
        $data['userList'] = $userList;
        $uid = auth()->user()->id;
        $wechatgroup1 = WechatGroup::select("wechat_groups.id","wechat_groups.name")
            ->join('wechat_group_users','wechat_group_users.gid','=','wechat_groups.id')
            ->where(function($query)use($uid){
                $query->where('wechat_group_users.uid',$uid);
            })->get()->toArray();
        $wechatgroup2 = WechatGroup::select("wechat_groups.id","wechat_groups.name")->where('wechat_groups.uid',$uid)->get()->toArray();
        $data['wechatgroup'] = array_merge($wechatgroup1,$wechatgroup2);
        return view('admin.wechat.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if(empty($request->wx_num))  return redirect()->back()->withErrors("微信号不能为空！");
        if(empty($request->wx_nike))  return redirect()->back()->withErrors("微信昵称不能为空！");
        $wx_nums = $request->get('wx_num');
        $wx_numArr = explode("\n",$wx_nums);
        foreach (array_keys($this->fields) as $field) {
            if ($field == 'uid') {
                if (auth()->user()->id != 1) {
                    $wxArr[$field]=getTid(auth()->user()->id);
                    continue;
                }
            }
            if ($field == 'username') {
                if (auth()->user()->id != 1) {
                    $wxArr[$field]=auth()->user()->name;
                    continue;
                }
            }
            if($field=='wx_num'){
                continue;
            }
            if($field=='tid'){
                $wxArr[$field] = getTid(auth()->user()->id);
                continue;
            }
            $wxArr[$field] = $request->get($field);
        }
        $wxArrs = [];$qc = [];
		$msg= '';$dsg='';$wx_nums='';
		$wechats = Wechat::lists('wx_num')->toArray();
        foreach($wx_numArr as $wx){
            $wx_num = trim($wx);
            if(in_array($wx_num,$qc)){ //如果重复数组,跳过
				$msg.=$wx_num.'、';
                continue;
            }else{
                $qc[]=$wx_num;
				$wx_nums.=$wx_num.'、';
            }
			
			if(!in_array($wx_num,$wechats)){
				$wxArr['wx_num']=$wx_num;
                $wxArrs[]=$wxArr;
			}else{
				$dsg.=$wx_num.'、';
			}
        }
        $wechat = new Wechat();
        $wechat->insert($wxArrs);
		event(new \App\Events\userActionEvent('\App\Models\Wechat',0, 1, '新增微信['.$wx_nums.']'));
		return redirect('/admin/wechat')->withSuccess('添加成功！重复：'.$msg.' 已存在数据库：'.$dsg);
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $wechat = Wechat::find((int)$id);
        if (!$wechat) return redirect('/admin/wechat')->withErrors("找不到该微信号!");
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $wechat->$field);
        }
        $data['id'] = (int)$id;
        $userList = User::lists('name', 'id');
        $data['userList'] = $userList;
        $uid = auth()->user()->id;
        $wechatgroup1 = WechatGroup::select("wechat_groups.id","wechat_groups.name")->join('wechat_group_users','wechat_group_users.gid','=','wechat_groups.id')->where(function($query)use($uid){
            $query->where('wechat_group_users.uid',$uid);
        })->get()->toArray();
        $wechatgroup2 = WechatGroup::select("wechat_groups.id","wechat_groups.name")->where('wechat_groups.uid',$uid)->get()->toArray();
        $data['wechatgroup'] = array_merge($wechatgroup1,$wechatgroup2);
        return view('admin.wechat.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, ['wx_num' => 'required|unique:wechats,id,' . $id]);
        $wechat = Wechat::find((int)$id);
        $status = $wechat->status;//原状态，判断是否需要更新模板
        foreach (array_keys($this->fields) as $field) {
            if ($field == 'uid') {
                continue;
            }
            if($field=='tid'){
                continue;
            }
            $wechat->$field = $request->get($field);
        }
        $wechat->save();
        //查询添加了该微信的分组
        if($status!=$request->get('status')){
            $groups = Group::where('wechat_list','LIKE','%'.$wechat->wx_num.'%')->get();
            foreach($groups as $group){
                $wechat_list = explode(',',$group->wechat_list);
                if(in_array($request->get('wx_num'),$wechat_list)){
                    //调用更新模板函数
                    $r = new Request();
                    $r->id = $group->id;
                    $domain = new DomainController();
                    $domain->crossGUpTpl($r);
                }
            }
        }
		event(new \App\Events\userActionEvent('\App\Models\Wechat',$id, 3, '更新微信['.$wechat->wx_num.']'));
        return redirect('/admin/wechat')->withSuccess('更新成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (is_numeric($id)) {
            $tag = Wechat::find((int)$id);
            if ($tag) {
				$wx_num = $tag->wx_num;
                $tag->status = 0;
                $tag->save();
                //查询添加了该微信的分组
                //if($status!=$request->get('status')){
                $groups = Group::where('wechat_list','LIKE','%'.$tag->wx_num.'%')->get();
                foreach($groups as $group){
                    $wechat_list = explode(',',$group->wechat_list);
                    if(in_array($tag->wx_num,$wechat_list)){
                        //调用更新模板函数
                        $r = new Request();
                        $r->id = $group->id;
                        $domain = new DomainController();
                        $domain->crossGUpTpl($r);
                    }
                }
                //}
                $tag->delete();
				event(new \App\Events\userActionEvent('\App\Models\Wechat',$id, 2, '删除微信['.$wx_num.']'));
            } else {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        } else {
            $idArr = explode(',', $id);
            $recordRows = Wechat::whereIn('id', $idArr)->get();
            foreach($recordRows as $rr){
                $rr->status = 0;
                $rr->save();
                //查询添加了该微信的分组
                $groups = Group::where('wechat_list','LIKE','%'.$rr->wx_num.'%')->get();
                foreach($groups as $group){
                    $wechat_list = explode(',',$group->wechat_list);
                    if(in_array($rr->wx_num,$wechat_list)){
                        //调用更新模板函数
                        $r = new Request();
                        $r->id = $group->id;
                        $domain = new DomainController();
                        $domain->crossGUpTpl($r);
                    }
                }
            }
			$wx_nums = '';
			$ws = Wechat::whereIn('id', $idArr)->get();
			foreach($ws as $w){$wx_nums.=$w->wx_num."、";}
            $recordRow = Wechat::whereIn('id', $idArr)->delete();
			event(new \App\Events\userActionEvent('\App\Models\Wechat',0, 2, '删除微信['.$wx_nums.']'));
            if (!$recordRow) {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }
        return redirect()->back()
            ->withSuccess("删除成功");
    }

	//取消/申请回收
		public function recover(Request $request){
			if($request->get('type')=='recover'){
				if (is_numeric($request->id)) {
					$tag = Wechat::find((int)$request->id);
					if ($tag&&$tag->recover==0) {
						$tag->recover = 1;
						$tag->save();
						$wr = new WechatRecover();
						$wr->wid = $tag->id;
						$wr->aid = auth()->user()->id;
						$wr->wid = $tag->id;
						$wr->save();
						event(new \App\Events\userActionEvent('\App\Models\Wechat',$tag->id, 3, '申请回收微信['.$tag->wx_num.']'));
					} else {
						return redirect()->back()
							->withErrors("申请失败");
					}
				} else {
					$idArr = explode(',', $request->id);
					$recordRow = Wechat::whereIn('id', $idArr)->get();
					foreach($recordRow as $rr){
						if($rr->recover==0){
							$rr->recover = 1;
							$rr->save();
							$wr = new WechatRecover();
							$wr->wid = $rr->id;
							$wr->aid = auth()->user()->id;
							$wr->save();
							event(new \App\Events\userActionEvent('\App\Models\Wechat',$rr->id, 3, '申请回收微信['.$rr->wx_num.']'));
						}
					}
					if (!$recordRow) {
						return redirect()->back()
							->withErrors("申请失败");
					}
				}
				return redirect()->back()
							->withSuccess("申请成功");
			}elseif($request->get('type')=='stop'){
				if (is_numeric($request->id)) {
					$tag = Wechat::find((int)$request->id);
					if ($tag&&$tag->recover==1) {
						$tag->recover = 0;
						$tag->save();
						$wr = WechatRecover::where('hid',0)->where('wid',$tag->id)->delete();
					} else {
						return redirect()->back()
							->withErrors("取消失败");
					}
			} else {
				$idArr = explode(',', $request->id);
				$recordRow = Wechat::whereIn('id', $idArr)->get();
				foreach($recordRow as $rr){
					$rr->recover = 0;
					$rr->save();
					$wr = WechatRecover::where('hid',0)->where('wid',$rr->id)->delete();
				}
				if (!$recordRow) {
					return redirect()->back()
						->withErrors("取消失败");
				}
			}
			return redirect()->back()
						->withSuccess("取消成功");
		}		
	}
    public function leading($id = 0)
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $userList = User::lists('name', 'id');
        $data['userList'] = $userList;
        $uid = auth()->user()->id;
        $data['wechatgroup'] = WechatGroup::select('wechat_groups.id', 'wechat_groups.name', 'admin_users.name as username')->leftJoin('admin_users', 'admin_users.id', '=', 'wechat_groups.uid')->where(function ($query) use ($uid) {
            if ($uid != 1) {
                $query->where('uid', '=', auth()->user()->id)->orWhere('uid', '=', 1);
            }
        })->get();
        return view('admin.wechat.leading', $data);
    }

    public function import(Request $request)
    {
        $file = $request->file('wechat');
        if ($request->hasFile('wechat')) {
            if ($file->isValid()) {
                $str = explode('.', $file->getClientOriginalName());
                $fileName = time() . '.' . $str[count($str) - 1];
                $file->move(config('app.templates_txt_path'), $fileName);
                unset($file);
                //$sevencattle->$field = $file->move(config('app.templates_txt_path'),$fileName);
                $contents = $this->file_utf8(config('app.templates_txt_path') . '/' . $fileName);
                $contentArr = explode('!@#!@#', $contents);
                $log_txt = "";$wx_nums='';

				foreach (array_keys($this->fields) as $field) {
					$data[$field] = $request->get($field);
				}
				if (auth()->user()->id == 1) {
					$data['uid'] = $request->get('uid');
					$data['username'] = $this->getUserName($request->get('uid'));
				} else {
					$data['uid'] = auth()->user()->id;
					$data['username'] = auth()->user()->name;
				}
				$wx_arr = $this->getWechatWxs();dd($wx_arr);
                foreach ($contentArr as $content) {
                    if (trim($content) != "") {
                        if (in_array(trim($content),$wx_arr)||trim($content)==''||trim($content)==null) {
                            $log_txt .= trim($content) . "\n";
                            continue;
                        }
						$wx_arr[] = trim($content);//如果通过，新增加到判断组
                        $data['wx_num'] = trim($content);
						$wx_nums.=trim($content)."、";
                        $datas[] = $data;
                    }
                }
				Wechat::insert($datas);
                unset($contentArr);
                unlink(config('app.templates_txt_path') . '/' . $fileName);
				event(new \App\Events\userActionEvent('\App\Models\Wechat',0, 1, '导入微信['.$wx_nums.']'));
                if ($log_txt != "") {
                    file_put_contents(config('app.templates_txt_path') . '/' . $fileName . '.log', $log_txt);
                    unset($fileName);
                    unset($log_txt);
                    return redirect('/admin/wechat')->withSuccess('导入成功！冲突日志：http://' . $_SERVER["HTTP_HOST"] . '/uploads/' . $fileName . '.log');
                } else {
                    unset($log_txt);
                    return redirect('/admin/wechat')->withSuccess('导入成功！没有冲突微信。');
                }

            } else {
                return redirect('/admin/wechat')->withErrors('文件无效！');
            }
        } else {
            return redirect('/admin/wechat')->withErrors('请上传文件！');
        }
    }

	public function getWechatWxs(){
		return Wechat::lists('wx_num')->toArray();
	}

    //转码
    public function file_utf8($filepath)
    {
        $f_contents = file_get_contents($filepath);
        $encoding = mb_detect_encoding($f_contents, array('GB2312', 'GBK', 'UTF-16', 'UCS-2', 'UTF-8', 'BIG5', 'ASCII'));
        $content_u = "";
        $hz = substr($filepath, strrpos($filepath, '.') + 1);
        if (strstr($hz, "csv")) {
            $filepath = fopen($filepath, 'r');
            while ($data = fgetcsv($filepath)) { //每次读取CSV里面的一行内容
                if ($encoding != false) {
                    $buffer = iconv($encoding, 'UTF-8', $data[0]);
                } else {
                    $buffer = mb_convert_encoding($data[0], 'UTF-8', 'Unicode');
                }
                $content_u .= $buffer . '!@#!@#';
            }
            fclose($filepath);
        } elseif (strstr($hz, "txt")) {
            $handle = fopen($filepath, "r");
            if ($handle) {
                while (!feof($handle)) {
                    $buffer = fgets($handle);
                    if ($encoding != false) {
                        $buffer = iconv($encoding, 'UTF-8', $buffer);
                    } else {
                        $buffer = mb_convert_encoding($buffer, 'UTF-8', 'Unicode');
                    }
                    $content_u .= $buffer . '!@#!@#';
                }
            }
            fclose($handle);
        }
        return $content_u;
    }

    public function getUserName($id)
    {
        $user = User::find((int)$id);
        return $user['name'];
    }

    /**
     *批量修改
     *随机值、状态、在线时间、标签
     */
    public function cogsUpdate(Request $request)
    {
        $update_id = $request->get('update_id');
        $update_id = explode(',', $update_id);
		$wx_nums='';
        foreach ($update_id as $ui) {
            $wechat = Wechat::find($ui);
            $status = $wechat->status;
            if ($request->get('max_rand') != null) $wechat->max_rand = $request->get('max_rand');
            if ($request->get('status') != -1) $wechat->status = $request->get('status');
            if ($request->get('group') != -1) $wechat->group = $request->get('group');
            if ($request->get('online_time') != null) $wechat->online_time = $request->get('online_time');
            if ($request->get('offline_time') != null) $wechat->offline_time = $request->get('offline_time');
            $wechat->save();
			$wx_nums.=$wechat->wx_num."、";
            if($status!=$request->get('status')){
                $groups = Group::where('wechat_list','LIKE','%'.$wechat->wx_num.'%')->get();
                foreach($groups as $group){
                    $wechat_list = explode(',',$group->wechat_list);
                    if(in_array($wechat->wx_num,$wechat_list)){
                        //调用更新模板函数
                        $r = new Request();
                        $r->id = $group->id;
                        $domain = new DomainController();
                        $domain->crossGUpTpl($r);
                    }
                }
            }
        }
		event(new \App\Events\userActionEvent('\App\Models\Wechat',0, 3, '批量更新微信['.$wx_nums.']'));
        return redirect('/admin/wechat');
    }
}